<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/excel')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDidlog=true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          :default-sort="{prop:'timeOfEntry', order: 'ascending'}"
          :data="list"
          border
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ hireTypeFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <!--方法1 <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button> -->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDidlog" @close="hClose">
        <emDialog ref="empDialog" @close="showDidlog=false" @success="hSuccess" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import emDialog from './empDialog.vue'
// import PageTools from '@/components/PageTools/index.vue'
import { getEmployee, delEmployee } from '@/api/employees'
import empLoyeesEnum from '@/constant/employees'

// const hireType = {}
// empLoyeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = empLoyeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    emDialog
  },
  data() {
    return {
      showDidlog: false, // 控制弹层显示和隐藏
      list: [], // 保存员工列表
      page: 1, // 页码
      size: 5, // 每页条数
      total: 0 // 总条数
    }
  },
  created() {
    this.loadEmployee() // 员工列表
  },
  methods: {
    // 控制每页条数切换
    handleSizeChange(val) {
      this.page = 1
      this.size = val
      this.loadEmployee()
      console.log(`每页 ${val} 条`)
    },
    // 控制页码值的切换
    handleCurrentChange(val) {
      this.page = val
      this.loadEmployee()
      console.log(`当前页: ${val}`)
    },
    hireTypeFormat(data) {
      // return empLoyeesEnum.hireType.find(item => item.id === data).value
      return hireType[data] || '未知'
    },
    // 加载员工列表
    async loadEmployee() {
      try {
        const res = await getEmployee(this.page, this.size)
        if (res.code === 10000) {
          this.list = res.data.rows
          this.total = res.data.total
          console.log(res, 'res')
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 增加完员工后重新渲染数据 关闭弹层
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployee()
      this.showDidlog = false
    },
    // 重置表单
    hClose() {
      this.$refs.empDialog.resetForm()
    },
    // 删除员工
    hDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployee()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async handleDownload() {
      try {
        const res = await getEmployee(this.page, this.size)
        if (res.code !== 10000) return
        console.log(res.data.rows, 'res.data.rows')
        const { headers, data } = this.dataFome(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
          // const tHeader = ['姓名', '手机号']
          // const data = [['张三', 1595556421], ['鲁北', 1595556421]]
          excel.export_json_to_excel({
            header: headers,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    dataFome(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 获取表头
      const one = list[0]
      let headers = []
      if (one) {
        headers = Object.keys(one).map(enkey => {
          return mapInfo
        })
      }
      const data = list.map(item => {
        return Object.values(item)
      })
      // console.log(headers);
      // console.log(data);
      return { headers, data }
    }
  }
}

</script>
